# Create your views here.
from django.http import HttpResponse
from .models import *
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import *
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth.decorators import login_required
from django.db.models import Avg

@csrf_exempt
def regist(request):
  if request.method == 'POST':
      name = request.POST.get('name')
      email = request.POST.get('email')
      password = request.POST.get('password')
      if User.objects.filter(username=name).exists():
        message = "The username has already been existed. Please change one."
      else:
        User.objects.create_user(username=name, email=email, password=password)
        message = "Register success"
      return HttpResponse(message)


@csrf_exempt
def login_view(request):
  if request.method == 'POST':
      name = request.POST.get('name')
      password = request.POST.get('password')
      user = authenticate(request, username=name, password=password)
      if user is not None:
        login(request, user)
        message = "Log in success"
      else:
        message = "Wrong username or password"
  return HttpResponse(message)


@csrf_exempt
def logout_view(request):
    logout(request)
    return HttpResponse("Log out success")


@csrf_exempt
def list(request):
  modules = Module_Instance.objects.all()
  info = {}
  for index, instance in enumerate(modules):
    module_info = {
      'code':instance.module.code,
      'name':instance.module.name,
      'year':instance.open_times.year,
      'semester':instance.open_times.semester,
      'professors':[(professor.id,professor.name) for professor in instance.teaching_professors.all()]
    }
    info[index]=module_info
  return HttpResponse(json.dumps(info, ensure_ascii=False), content_type="application/json")


@csrf_exempt
def rating(request):
  if request.user.is_authenticated:
    professor_id = request.POST.get('professor_id')
    module_code = request.POST.get('module_code')
    year = request.POST.get('year')
    semester = request.POST.get('semester')
    rating = request.POST.get('rating')
    user_id = request.user.id
    module = Module_Instance.objects.filter(module__code=module_code,open_times__year=year,open_times__semester=semester)
    professor = Professor.objects.filter(id=professor_id)
    if module.exists() and professor.exists():
      rate = Rating.objects.filter(module=module[0],professor=professor[0],user_id=user_id)
      if rate.exists():
        rate[0].rating = rating
        rate[0].save()
        msg = "Rating changed."
      else:
        Rating.objects.create(module=module[0],professor=professor[0],user_id=user_id,rating=rating)
        msg = "Success rating."
    else:
      msg = "Module or Professor does not exist."
  else:
    msg = "Please log in first."
  return HttpResponse(msg)


@csrf_exempt
def view(request):
  professors = Professor.objects.all()
  info = dict()
  for i, p in enumerate(professors):
    average_rating = Rating.objects.filter(professor__id=p.id).aggregate(Avg('rating'))
    info[i]={'name':p.name,'id':p.id, 'rating':round(average_rating['rating__avg'])}
  return HttpResponse(json.dumps(info, ensure_ascii=False), content_type="application/json")


@csrf_exempt
def average(request):
  professor_id = request.POST.get('professor_id')
  module_code = request.POST.get('module_code')
  average_rating = Rating.objects.filter(module__module__code=module_code,professor__id=professor_id).aggregate(Avg('rating'))
  info = {
    'professor_name': Professor.objects.get(id=professor_id).name,
    'professor_id':professor_id,
    'module_code':module_code,
    'module_name': Module.objects.get(code=module_code).name,
    'rating': round(average_rating['rating__avg'])
  }
  return HttpResponse(json.dumps(info, ensure_ascii=False), content_type="application/json")
